package irri.soils.ssnm;

import java.text.DecimalFormat;
import java.util.HashMap;

import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.inputmethodservice.KeyboardView;
import android.inputmethodservice.KeyboardView.OnKeyboardActionListener;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.text.Selection;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

public class SSNM extends Activity implements OnKeyboardActionListener{
	public static SSNM prevActivity;
	private SQLiteDatabase myDB;
	public String lv_arr[];
	public String lv_arr2[] = {"", "0", ""};
	private boolean customTitleSupported;
	public KeyboardView mInputView;
	public LatinKeyboard mSymbolsKeyboard;
	public static String[] initialD = {"", "i_", "b_", "h_", "c_", "t_"};
	public static int d = -1;
	public DecimalFormat df = new DecimalFormat("#.##");
	public static HashMap<String, String> responses;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
	}
	
	public void setCustomTitle(){
        if (customTitleSupported)
            getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true; 
    }
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	Intent intent;
    	prevActivity = this;
    	Bundle b = this.getIntent().getExtras();
    	switch (item.getItemId()) {
            case R.id.language: 
            	try {
                    myDB = this.openOrCreateDatabase("SSNM2", 
                    		MODE_WORLD_WRITEABLE, null);
                    myDB.execSQL("CREATE TABLE IF NOT EXISTS lang (lang INT(3));");
                    myDB.execSQL("DELETE FROM lang;");
	            	intent = new Intent(this, ActivityA.class);
	            	intent.putExtras(b);
	            	startActivity(intent);
	            }
            	catch(Exception e) {
                    Log.e("Error", "Error", e);
                   } finally {
                    if (myDB != null) myDB.close();
                }
                finish();
                break;
            case R.id.person: 
            	try {
                    myDB = this.openOrCreateDatabase("SSNM2", 
                    		MODE_WORLD_WRITEABLE, null);
                    myDB.execSQL("CREATE TABLE IF NOT EXISTS owner2 (name varchar(50) " +
        	         		"NOT NULL, num varchar(12) NOT NULL, email varchar(50) " +
        	         		"NOT NULL);");
                    myDB.execSQL("DELETE FROM owner2;");
                    //System.out.println(b.getString("exten_name"));
	            	intent = new Intent(this, ActivityMain5.class);
	            	intent.putExtras(b);
	            	startActivity(intent);
	            }
            	catch(Exception e) {
                    Log.e("Error", "Error", e);
                   } finally {
                    if (myDB != null) myDB.close();
                }
                finish();
                break;
            case R.id.history:
            	if(checkInternetConnection()){
            	intent = new Intent(this, ActivityMain4.class);
            	intent.putExtras(b);
            	startActivity(intent);
            	finish();
            	}else{
            		displayToast("No available Internet connection.");
            	}
                break;
            case R.id.save:
            	intent = new Intent(this, ActivityMain6.class);
            	intent.putExtras(b);
            	startActivity(intent);
            	finish();
            	break;
            case R.id.about: 
            	intent = new Intent(this, ActivityU.class);
            	intent.putExtras(b);
            	startActivity(intent);
            	finish();
                break;
        }
        return true;
    }
    
    public void displayToast(String message){
		Toast toast = Toast.makeText(this, message, Toast.LENGTH_LONG);
		toast.setGravity(Gravity.TOP|Gravity.CENTER, 0, 0);
		toast.show();
	}

	@Override
	public void onKey(int arg0, int[] arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPress(int arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onRelease(int arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onText(CharSequence text) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void swipeDown() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void swipeLeft() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void swipeRight() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void swipeUp() {
		// TODO Auto-generated method stub
	}
	
	public void onDelete(TextView tv, String str){
		String strcpy = str;
		int cursor = tv.getSelectionStart();
		str = strcpy.substring(0, cursor-1);
		if(cursor!=strcpy.length()) str += strcpy.substring(cursor);
		tv.setText("");
		tv.append(str);
		Selection.setSelection(tv.getEditableText(), cursor-1);
	}
	
	public void onDigit(TextView tv, String str, int primaryCode){
		String strcpy = str;
		int cursor = tv.getSelectionStart();
		str = strcpy.substring(0, cursor)+String.valueOf((char) primaryCode);
		if(cursor!=strcpy.length()) str += strcpy.substring(cursor);
		tv.setText("");
		tv.append(str);
		Selection.setSelection(tv.getEditableText(), cursor+1);
	}
	
	public boolean checkInternetConnection() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        // test for connection
        if (cm.getActiveNetworkInfo() != null
                && cm.getActiveNetworkInfo().isAvailable()
                && cm.getActiveNetworkInfo().isConnected()) {
            return true;
        } else {
        	//option1.setText("Internet Connection Not Present");
            return false;
        }
    }
	
	public String processHttp(String address) throws Exception {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(address);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = httpClient.execute(httpGet, responseHandler);
        /* For debugging html
        File file = new File(Environment.getExternalStorageDirectory().toString(), "log.html");
        OutputStream outStream = new FileOutputStream(file);
        outStream.write(response.getBytes());
        outStream.close();
        */
        return response;
    }
	
	//---sends an SMS message to another device---
    public void sendSMS(String phoneNumber, String message)
    {        
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";
        System.out.println(message);
        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
            new Intent(SENT), 0);
 
        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
            new Intent(DELIVERED), 0);
 
        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "GENERIC FAILURE", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off", 
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));
 
        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;                        
                }
            }
        }, new IntentFilter(DELIVERED));
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);        
    }
    
    public void messageProcess(String response, String number){
    	String sms = response.split("<!--SMS-->")[1];
		String[] bisect = sms.split("<!--ref-->");
		String ref = bisect[1];
		String recom = bisect[2].replace("&amp;", "&");
		String[] parts = recom.split("<>");
		for(int i=0; i<parts.length-1; i++){
			String combine = parts[i]+" "+parts[i+1];
			if(combine.length()<130) parts[i] = combine;
		}
		int counter = 0;
		for(int i=0; i<parts.length&&!parts[i].equals(""); i++){
			counter++;
		}
			
		for(int i=0; i<counter; i++)
		sendSMS(number, "NMRICE "+(i+1)+"/"+counter+" "+ref+" "+parts[i]);
		SQLiteDatabase myDB= null;
		try {
            myDB = this.openOrCreateDatabase("SSNM2", MODE_WORLD_WRITEABLE, null);
            
            Cursor c = myDB.rawQuery("SELECT last_insert_rowid()", null);
            if (c != null) {
                c.moveToFirst();
                myDB.execSQL("DELETE FROM phil where ref_id = "+c.getInt(0));
                c.close();
            }
        }
        catch(Exception e) {
        } finally {
           if(myDB!=null) myDB.close();
        }
    }
    
    public void deleteStored(int ref_id){
    	SQLiteDatabase myDB= null;
		try {
            myDB = this.openOrCreateDatabase("SSNM2", MODE_WORLD_WRITEABLE, null);
            System.out.println("Ref id: "+ref_id);
            myDB.execSQL("DELETE FROM phil where ref_id = "+ref_id);
        }
        catch(Exception e) {
        } finally {
           if(myDB!=null) myDB.close();
        }
    }
    
    public int getArrayCode(String id){
    	return getResources().getIdentifier(initialD[d]+id, "array", getPackageName());
    }
    
    public String get(String id){
    	int code = getResources().getIdentifier(initialD[d]+id, "string", getPackageName());
    	String value = code == 0 ? "" : (String) getResources().getText(code);
    	return value;
    }
}
